//Visit http://www.simplecodestuffs.com/file-upload-with-progress-bar-using-jquery-in-servlet/
package net.codesree.action;

import java.io.File;
import java.io.IOException;

import java.util.List;

import javax.servlet.ServletException;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import net.action.AbstractAction;
import net.action.utils.UploadListener;

public class UploadAction extends AbstractAction {

  private boolean isReqGet=true;
  private String UPLOAD_DIRECTORY=null;
  
  public UploadAction() {
	this.fromUrl="";
	this.nextUrl=null;
  }
  
  public void preProcess() throws IOException,ServletException {
	if(this.req.getMethod().equalsIgnoreCase("GET"))
	 this.isReqGet=true;
  }
  
  public void processRequest() throws IOException,ServletException {
	if(this.isReqGet) {
	  nextUrl=fromUrl;
	} else {
	 boolean isMultipart=ServletFileUpload.isMultipartContent(this.req);
	 if(isMultipart) {
	   //Create a factory for disk-based file items
	   FileItemFactory factory=new DiskFileItemFactory();
	   //Create a new file upload handler
	   ServletFileUpload upload=new ServletFileUpload(factory);
	   UploadListener listener=new UploadListener();
	   upload.setProgressListener(listener);
	   try {
        //Parse the request
		List<FileItem> multiparts=upload.parseRequest(req);
		for(FileItem item : multiparts) {
		  if(!item.isFormField()) {
			  String name=new File(item.getName()).getName();
			  item.write(new File(UPLOAD_DIRECTORY + File.separator + name));
		  }
		}		   
	   } catch (Exception ex) {
        System.out.println("File Upload failed.");		   
	   }
	 } else {
	  System.out.println("Request not multipart");
	 }
	}
  }
  
  public void postProcess() throws IOException,ServletException {
	if(this.isReqGet) {
	  forward();
	} else {} 
  }

}